Wang Haihua
🍈 🍉🍊 🍋 🍌
现在已知数据
x = [1,2,3,4,5,6]
y = [300,500,800,1300,3000,5000]
绘制函数图像:
import matplotlib.pyplot as plt # 导入matplotlib库中的pyplot模块,并命名为plt
%matplotlib inline
x = [1,2,3,4,5,6]
y = [300,500,800,1300,3000,5000]
plt.scatter(x,y) # 绘制散点图
我们希望对x,y关系进行拟合,设定函数形式为: $$y = ae^{kx}$$
借助scipy
,可以获得系数$a,k$的值.
首先定义函数:
# 定义函数
def func(x,a,k): # 自变量要放在第一个
return a*np.e**(k*x)
接下来调用curvefit
进行拟合:
from scipy.optimize import curve_fit
(a,k),_ = curve_fit(func,x,y) # 调用拟合函数,依次输入(函数,自变量取值,因变量取值)
结果为
a=137.86824487839056,k= 0.6003825942342587
所以最终的函数为 $$y=137.87e^{0.60x}$$
拟合效果图:
import matplotlib.pyplot as plt # 导入matplotlib库中的pyplot模块,并命名为plt
%matplotlib inline
import numpy as np
x = [1,2,3,4,5,6]
y = [300,500,800,1300,3000,5000]
plt.scatter(x,y) # 绘制散点图
plt.savefig('images/sci0101.png')
def func(x,a,k): # 自变量要放在第一个
return a*np.e**(k*x)
from scipy.optimize import curve_fit
(a,k),_ = curve_fit(func,x,y) # 调用拟合函数,依次输入(函数,自变量取值,因变量取值)
a,k
(137.86824487839056, 0.6003825942342587)
x = [1,2,3,4,5,6]
y = [300,500,800,1300,3000,5000]
y_fit = [func(i,a,k) for i in x]
plt.scatter(x,y,label='original data') # 绘制散点图
plt.plot(x,y_fit,label='fitted line',color='red')
plt.legend()
plt.savefig('images/sci0102.png')